package com.situ.web.dao.impl;

import com.situ.web.dao.IStudentDao;
import com.situ.web.pojo.Student;
import com.situ.web.pojo.vo.StudentBanjiVO;
import com.situ.web.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl implements IStudentDao {
    @Override
    public int add(Student student) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        int count = 0;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "insert into student(name,age,gender,banji_id) values(?,?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, student.getName());
            preparedStatement.setInt(2, student.getAge());
            preparedStatement.setString(3, student.getGender());
            preparedStatement.setInt(4, student.getBanjiId());
            System.out.println(preparedStatement);
            count = preparedStatement.executeUpdate();
            System.out.println("count: " + count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, preparedStatement, null);
        }

        return count;
    }

    @Override
    public List<StudentBanjiVO> selectAll() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<StudentBanjiVO> list = new ArrayList<>();
        try {
            connection = JDBCUtil.getConnection();
            String sql = "SELECT s.id,s.name,s.age,s.gender,b.name AS banjiName,b.address\n" +
                    "FROM student AS s INNER JOIN banji AS b\n" +
                    "ON s.banji_id=b.id";
            //预编译
            preparedStatement = connection.prepareStatement(sql);
            System.out.println(preparedStatement);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {//判断下一个有没有，如果返回true而且指向下一个，没有返回false
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                String banjiName = resultSet.getString("banjiName");
                String address = resultSet.getString("address");
                StudentBanjiVO studentBanjiVO = new StudentBanjiVO(id, name, age, gender, banjiName, address);
                list.add(studentBanjiVO);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, preparedStatement, resultSet);
        }

        return list;
    }
}
